package com.tedu.egweibo.controller;

import com.tedu.egweibo.mapper.IUserMapper;
import com.tedu.egweibo.pojo.dto.UserLoginDTO;
import com.tedu.egweibo.pojo.dto.UserRegDTO;
import com.tedu.egweibo.pojo.entity.User;
import com.tedu.egweibo.pojo.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;

@RestController
@RequestMapping("/v1/users")
public class UserController {

    @Autowired
    private IUserMapper iUserMapper;

    @PostMapping("/reg")
    public int register(@RequestBody UserRegDTO userRegDTO){
        User userV = iUserMapper.verify(userRegDTO.getUsername());
        if(userV!=null){
            return 2;//用户名已存在
        }
        User user = new User();
        BeanUtils.copyProperties(userRegDTO,user);
        user.setCreated(new Date());
        iUserMapper.insert(user);
        return 1;//注册成功
    }

    @PostMapping("/login")
    public int login(@RequestBody UserLoginDTO userLoginDTO, HttpSession session){
        User userV = iUserMapper.verify(userLoginDTO.getUsername());
        if(userV==null){
            return 3;//用户名错误
        }
        if(!userV.getPassword().equals(userLoginDTO.getPassword())){
            return 2;//密码错误
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(userV,userVO);
        session.setAttribute("user",userVO);

        return 1;//登录成功

    }

    @GetMapping("/currentUser")
    public UserVO currentUser(HttpSession session){
        UserVO userVO = (UserVO)session.getAttribute("user");
        if(userVO==null){
            System.out.println("未登录，请登录");
            return null;
        }
        return userVO;
    }

    @GetMapping("/logout")
    public void logout(HttpSession session){
        session.removeAttribute("user");
        System.out.println("已退出登录");

    }
}
